package fr.hoteia.appengine.archetype.server.web.clickstream;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.opensymphony.clickstream.Clickstream;
import com.opensymphony.clickstream.ClickstreamFilter;
import com.opensymphony.clickstream.ClickstreamListener;

public class ExtClickstreamFilter extends ClickstreamFilter {

    private static final Log log = LogFactory.getLog(ExtClickstreamFilter.class);

    /**
     * Attribute name indicating the filter has been applied
     * to a given request.
     */
    private final static String FILTER_APPLIED = "_clickstream_filter_applied";
    
	@Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // Ensure that filter is only applied once per request.
        if (request.getAttribute(FILTER_APPLIED) == null) {
            if (log.isDebugEnabled()) {
                log.debug("Applying clickstream filter to request.");
            }

            request.setAttribute(FILTER_APPLIED, Boolean.TRUE);

            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            String path = httpServletRequest.getContextPath();
            System.out.println(path);
            if(path.startsWith("/sc")){
            	// Nothing
            } else {
                HttpSession session = ((HttpServletRequest) request).getSession();
                Clickstream stream = (Clickstream) session.getAttribute(ClickstreamListener.SESSION_ATTRIBUTE_KEY);
                if(stream != null){
                    stream.addRequest(httpServletRequest);
                }
            }
        }
        else {
            if (log.isDebugEnabled()) {
                log.debug("Clickstream filter already applied, ignoring it.");
            }
        }

        // pass the request on
        chain.doFilter(request, response);
    }
}
